import React, { ReactElement, useState, Fragment } from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi'

interface Props {
    index?: number,
    changeSkillItem: Function
}


function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

// 上传之前
function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

function Index({ index, changeSkillItem }: Props): ReactElement {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")
    function handleChange(info: any) {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            changeSkillItem(index, "icon", info.file.response.url)
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (imageUrl: string) => {
                setImageUrl(imageUrl)
                setLoading(false)
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <Fragment>
            <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/api/admin/api/upload/skill"
                beforeUpload={beforeUpload}
                onChange={handleChange}
                headers={{
                    Authorization: sessionStorage.getItem('token')
                }}
            >
                
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </Fragment>
    )
}

export default connect(() => {
    return {

    }
}, (dispatch) => {
    return {
        changeSkillItem(index: number, classify: string, value: string) {
            dispatch({ type: "heroCard/changeSkillItem", index, classify, value })
        }
    }
})(Index)
